package cn.schoolwow.quickdao.test.module.business.user.transaction.commit.flow;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.test.entity.Role;
import cn.schoolwow.quickdao.test.entity.User;
import cn.schoolwow.quickdao.test.entity.UserRole;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.junit.Assert;

public class CheckCommitUserRoleTransactionResultFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        checkUser(flowContext);
        checkRole(flowContext);
        checkUserRole(flowContext);
    }

    @Override
    public String name() {
        return "检查用户角色事务提交结果";
    }

    private void checkUser(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);
        User insertUser = (User) flowContext.checkData("insertUser");

        long count = dao.query(User.class)
                .addQuery("id", insertUser.getId())
                .execute()
                .count();
        Assert.assertEquals(1, count);
    }

    private void checkRole(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);
        Role insertRole = (Role) flowContext.checkData("insertRole");

        long count = dao.query(Role.class)
                .addQuery("id", insertRole.getId())
                .execute()
                .count();
        Assert.assertEquals(1, count);
    }

    private void checkUserRole(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);
        User insertUser = (User) flowContext.checkData("insertUser");
        Role insertRole = (Role) flowContext.checkData("insertRole");

        long count = dao.query(UserRole.class)
                .addQuery("userId", insertUser.getId())
                .addQuery("roleId", insertRole.getId())
                .execute()
                .count();
        Assert.assertEquals(1, count);
    }

}
